<?php


namespace app\utils;


class File
{

    public static function urlToTmpFile($url, $extension = '')
    {
        return self::contentToTmpFile(file_get_contents($url), $extension ?: pathinfo($url, PATHINFO_EXTENSION));
    }

    public static function contentToTmpFile($content, $extension = 'tmp')
    {
        $tmpFilePath = self::createTempFile($extension);
        file_put_contents($tmpFilePath, $content);
        return $tmpFilePath;
    }

    public static function createTempFile($extension)
    {
        return sys_get_temp_dir() . '/' . uniqid('tdh_') . '.' . $extension;
    }

    public static function showSize($size)
    {
        if ($size >= 1024 * 1024 * 1024) {
            return bcdiv($size, 1024 * 1024 * 1024, 2) . 'G';
        } else if ($size > 1024 * 1024) {
            return bcdiv($size, 1024 * 1024, 2) . 'M';
        } else if ($size > 1024) {
            return bcdiv($size, 1024, 2) . 'k';
        }
        return $size . 'b';
    }

    public static function getTemplatePath($extension = 'tmp')
    {
        return sys_get_temp_dir() . '/' . uniqid() . ".{$extension}";
    }
}
